package com.ubaer.zsycz.components.okhttp;


import android.annotation.SuppressLint;

import com.lsw.shareUser.ShareUserInfoUtil;
import com.lsw.util.LogUtils;
import com.lsw.util.NetworkUtil;
import com.lsw.util.StringUtil;
import com.ubaer.zsycz.MyApplication;
import com.ubaer.zsycz.components.exception.NoNetworkException;
import com.ubaer.zsycz.inject.Constants;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * author：lsw
 */
public class LoggingInterceptor implements Interceptor {
    @SuppressLint("LongLogTag")
    @Override
    public Response intercept(Chain chain) throws IOException {

        if (!NetworkUtil.isNetworkConnected(MyApplication.getMyApplication())) {
            throw new NoNetworkException("请开启网络连接！");
        } else if (!NetworkUtil.isMobileConnected(MyApplication.getMyApplication()) &&
                !NetworkUtil.isWifiConnected(MyApplication.getMyApplication())) {
            throw new NoNetworkException("当前网络不可用！");
        }
        Request request = chain.request();
        LogUtils.i("http--------", "request=" + request.toString());
        if (LogUtils.logdebug) {
            if (request.body() instanceof FormBody) {
                FormBody oldFormBody = (FormBody) request.body();
                for (int i = 0; i < oldFormBody.size(); i++) {
                    LogUtils.i("http--------", "body:" + oldFormBody.encodedName(i) + "=" + oldFormBody.encodedValue(i));
                }
            }
        }
        Response response = null;
        if (StringUtil.isNullOrEmpty(ShareUserInfoUtil.getInstance(MyApplication.getMyApplication()).getString(ShareUserInfoUtil.USER_TOKEN, ""))) {
            Request tokenRequest = request.newBuilder()
                    .addHeader("Accept", Constants.ACCEPT)
                    .build();
            response = chain.proceed(tokenRequest);
        } else {
            Request tokenRequest = request.newBuilder()
                    .addHeader("authorization", ShareUserInfoUtil.getInstance(MyApplication.getMyApplication()).getString(ShareUserInfoUtil.USER_TOKEN, ""))
                    .addHeader("Accept", Constants.ACCEPT)
                    .build();
            LogUtils.i("http--------", "token=" + ShareUserInfoUtil.getInstance(MyApplication.getMyApplication()).getString(ShareUserInfoUtil.USER_TOKEN, ""));
            response = chain.proceed(tokenRequest);
        }
//        Response response = chain.proceed(request);
//此方法在header的content-length不确定的情况下会出错
        ResponseBody responseBody = response.peekBody(1024 * 1024);
        String gson = responseBody.string();
        LogUtils.e("responseBody.string() = ", gson + ",head=" + response.headers().toString());
        String token = response.header("authorization");
        if (!StringUtil.isNullOrEmpty(token)) {
            ShareUserInfoUtil.getInstance(MyApplication.getMyApplication()).setString(ShareUserInfoUtil.USER_TOKEN, token);
        }
        if (gson == null) {
            throw new NoNetworkException("后台数据异常！");
        }
        return response;
    }


    /**
     * 解析请求参数
     *
     * @param request
     * @return
     */
    public static Map<String, String> parseParams(Request request) {
        //GET POST DELETE PUT PATCH
        String method = request.method();
        Map<String, String> params = null;
        if ("GET".equals(method)) {
            params = doGet(request);
        } else if ("POST".equals(method) || "PUT".equals(method) || "DELETE".equals(method) || "PATCH".equals(method)) {
            RequestBody body = request.body();
            if (body != null && body instanceof FormBody) {
                params = doForm(request);
            }
        }
        return params;
    }

    /**
     * 获取get方式的请求参数
     *
     * @param request
     * @return
     */
    private static Map<String, String> doGet(Request request) {
        Map<String, String> params = null;
        HttpUrl url = request.url();
        Set<String> strings = url.queryParameterNames();
        if (strings != null) {
            Iterator<String> iterator = strings.iterator();
            params = new HashMap<>();
            int i = 0;
            while (iterator.hasNext()) {
                String name = iterator.next();
                String value = url.queryParameterValue(i);
                params.put(name, value);
                i++;
            }
        }
        return params;
    }

    /**
     * 获取表单的请求参数
     *
     * @param request
     * @return
     */
    private static Map<String, String> doForm(Request request) {
        Map<String, String> params = null;
        FormBody body = null;
        try {
            body = (FormBody) request.body();
        } catch (ClassCastException c) {
        }
        if (body != null) {
            int size = body.size();
            if (size > 0) {
                params = new HashMap<>();
                for (int i = 0; i < size; i++) {
                    params.put(body.name(i), body.value(i));
                }
            }
        }
        return params;
    }
}
